package com.zhouhailin.service.impl;

import com.zhouhailin.domain.LoginUser;
import com.zhouhailin.domain.ResponseResult;
import com.zhouhailin.entity.User;
import com.zhouhailin.service.LoginService;
import com.zhouhailin.utils.JwtUtil;
import com.zhouhailin.utils.RedisCache;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Objects;

/**
 * @author: zhouhailin
 * @Date : 2024/2/7
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {

        // 1、将用户输入的：用户名和密码，封装成 UsernamePasswordAuthenticationToken
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),
                user.getPassword());
        // 2、基于 AuthenticationManager 中的 authenticate方法进行用户认证【管理器中的认证方法】
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }
        // 使用 userid 生成 Token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        // authenticate存入redis
        redisCache.setCacheObject("login:" + userId, loginUser);
        // 将Token响应给前端
        HashMap<String, String> map = new HashMap<>();
        map.put("token", jwt);

        return new ResponseResult(200, "登录成功", map);
    }

    @Override
    public ResponseResult loginOut() {
        // 获取 SecurityContextHolder中的认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        // 获取Userid，并删除Redis中缓存数据
        Long userId = loginUser.getUser().getId();
        redisCache.deleteObject("login:" + userId);

        return new ResponseResult(200, "退出成功！");
    }
}
